const express = require('express');
const router = express.Router();
const db = require('../config/db');
const { v4: uuidv4 } = require('uuid');
const multer = require('multer');
const path = require('path');

// 配置 multer 存储
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public/uploads/');  // 上传文件存储路径
    },
    filename: function (req, file, cb) {
        // 生成唯一文件名
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname));
    }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
    // 只允许上传图片
    if (file.mimetype.startsWith('image/')) {
        cb(null, true);
    } else {
        cb(new Error('只允许上传图片文件！'), false);
    }
};

// 创建 multer 实例
const upload = multer({ 
    storage: storage,
    fileFilter: fileFilter,
    limits: {
        fileSize: 10 * 1024 * 1024  // 限制文件大小为 10MB
    }
});

// 修改图片上传路由，添加错误处理
router.post('/upload', function(req, res, next) {
    upload.single('file')(req, res, function(err) {
        if (err instanceof multer.MulterError) {
            // Multer 错误处理
            if (err.code === 'LIMIT_FILE_SIZE') {
                return res.status(400).json({
                    code: 400,
                    msg: '图片大小不能超过10MB',
                    data: null
                });
            }
            return res.status(400).json({
                code: 400,
                msg: '图片上传失败',
                data: null
            });
        } else if (err) {
            // 其他错误
            return res.status(400).json({
                code: 400,
                msg: err.message || '图片上传失败',
                data: null
            });
        }

        // 成功处理
        if (!req.file) {
            return res.status(400).json({
                code: 400,
                msg: '请选择要上传的图片',
                data: null
            });
        }

        // 返回图片URL
        const photoUrl = `/uploads/${req.file.filename}`;
        res.status(200).json({
            code: 200,
            msg: '图片上传成功',
            data: {
                url: photoUrl
            }
        });
    });
});

/* GET users listing. */
router.get('/', async function(req, res, next) {
    try {
        const [rows] = await db.pool.query('SELECT * FROM users');
        res.status(200).json({
            code: 200,
            msg: '获取用户列表成功',
            data: rows
        });
    } catch (err) {
        res.status(500).json({
            code: 500,
            msg: '获取用户列表失败',
            data: null
        });
    }
});

/* POST user signup/edit */
router.post('/signup', async function(req, res) {
    try {
        // 打印请求体，看看收到了什么数据
        console.log('Received request body:', req.body);

        let {
            id,
            name, gender, birth_year, hometown, contact,
            work_location, education, marital_status_desc,
            height, weight, zodiac, occupation, income,
            family, housing, car, hobbies, personality,
            accept_divorced, requirements, introduction,
            photo_urls
        } = req.body;

        // 检查必要字段是否存在
        if (!name || !gender || !birth_year || !hometown || !contact) {
            return res.status(400).json({
                code: 400,
                msg: '缺少必要字段',
                data: null
            });
        }

        // 设置默认值
        car = car || '否';
        accept_divorced = accept_divorced || '否';
        weight = weight || null;
        zodiac = zodiac || null;
        family = family || null;

        // 开始事务
        const connection = await db.pool.getConnection();
        await connection.beginTransaction();

        try {
            if (id) {
                // 编辑模式
                const [existingUser] = await connection.query(
                    'SELECT id FROM users WHERE id = ?',
                    [id]
                );

                if (existingUser.length === 0) {
                    await connection.rollback();
                    return res.status(404).json({
                        code: 404,
                        msg: '用户不存在',
                        data: null
                    });
                }

                // 更新用户数据
                await connection.query(
                    `UPDATE users SET 
                        name = ?, gender = ?, birth_year = ?, hometown = ?, contact = ?,
                        work_location = ?, education = ?, marital_status_desc = ?,
                        height = ?, weight = ?, zodiac = ?, occupation = ?, income = ?,
                        family = ?, housing = ?, car = ?, hobbies = ?, personality = ?,
                        accept_divorced = ?, requirements = ?, introduction = ?
                    WHERE id = ?`,
                    [
                        name, gender, birth_year, hometown, contact,
                        work_location, education, marital_status_desc,
                        height, weight, zodiac, occupation, income,
                        family, housing, car, hobbies, personality,
                        accept_divorced, requirements, introduction,
                        id
                    ]
                );

                // 处理照片
                if (photo_urls && Array.isArray(photo_urls) && photo_urls.length > 0) {
                    await connection.query(
                        'DELETE FROM photos WHERE user_id = ?',
                        [id]
                    );

                    const photoValues = photo_urls.map(url => [uuidv4(), id, url]);
                    await connection.query(
                        'INSERT INTO photos (id, user_id, url) VALUES ?',
                        [photoValues]
                    );
                }

            } else {
                // 添加模式
                id = uuidv4();
                await connection.query(
                    `INSERT INTO users (
                        id, name, gender, birth_year, hometown, contact,
                        work_location, education, marital_status_desc,
                        height, weight, zodiac, occupation, income,
                        family, housing, car, hobbies, personality,
                        accept_divorced, requirements, introduction
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, 
                        ?, ?, ?, 
                        ?, ?, ?, ?, ?,
                        ?, ?, ?, ?, ?,
                        ?, ?, ?
                    )`,
                    [
                        id, name, gender, birth_year, hometown, contact,
                        work_location, education, marital_status_desc,
                        height, weight, zodiac, occupation, income,
                        family, housing, car, hobbies, personality,
                        accept_divorced, requirements, introduction
                    ]
                );

                // 处理照片
                if (photo_urls && Array.isArray(photo_urls) && photo_urls.length > 0) {
                    const photoValues = photo_urls.map(url => [uuidv4(), id, url]);
                    await connection.query(
                        'INSERT INTO photos (id, user_id, url) VALUES ?',
                        [photoValues]
                    );
                }
            }

            await connection.commit();

            res.status(200).json({
                code: 200,
                msg: id ? '编辑成功' : '添加成功',
                data: {
                    id,
                    name,
                    contact,
                    photo_urls
                }
            });

        } catch (error) {
            console.error('数据库操作失败:', error);
            await connection.rollback();
            throw error;
        } finally {
            connection.release();
        }

    } catch (error) {
        console.error('操作失败:', error);
        console.error('错误详情:', error.stack);
        res.status(500).json({
            code: 500,
            msg: '服务器错误，操作失败',
            data: null
        });
    }
});

/* GET users list with filters */
router.get('/list', async function(req, res) {
    try {
        console.log('Query params:', req.query);
        const { name, contact, gender, page = 1, pageSize = 10 } = req.query;
        
        let sql = `
            SELECT 
                u.*,
                GROUP_CONCAT(p.url) as photo_urls
            FROM users u
            LEFT JOIN photos p ON u.id = p.user_id
        `;
        
        const params = [];
        const conditions = [];
        
        if (name) {
            conditions.push('u.name LIKE ?');
            params.push(`%${name}%`);
        }
        
        if (contact) {
            conditions.push('u.contact LIKE ?');
            params.push(`%${contact}%`);
        }

        if (gender) {
            conditions.push('u.gender = ?');
            params.push(gender);
        }
        
        if (conditions.length > 0) {
            sql += ' WHERE ' + conditions.join(' AND ');
        }
        
        // 添加分组
        sql += ' GROUP BY u.id';
        
        // 添加排序
        sql += ' ORDER BY u.created_at DESC';
        
        // 添加分页
        const offset = (page - 1) * pageSize;
        sql += ' LIMIT ? OFFSET ?';
        params.push(parseInt(pageSize), offset);

        console.log('Executing SQL:', sql);
        console.log('With params:', params);
        
        const [rows] = await db.pool.query(sql, params);
        
        // 获取总数
        let countSql = 'SELECT COUNT(DISTINCT u.id) as total FROM users u';
        if (conditions.length > 0) {
            countSql += ' WHERE ' + conditions.join(' AND ');
        }
        const [totalRows] = await db.pool.query(countSql, params.slice(0, -2));
        
        const formattedRows = rows.map(row => ({
            ...row,
            photo_urls: row.photo_urls ? row.photo_urls.split(',') : []
        }));

        res.status(200).json({
            code: 200,
            msg: '获取用户列表成功',
            data: {
                total: totalRows[0].total,
                list: formattedRows,
                page: parseInt(page),
                pageSize: parseInt(pageSize)
            }
        });

    } catch (error) {
        console.error('获取用户列表失败:', error);
        console.error('错误详情:', error.stack);
        res.status(500).json({
            code: 500,
            msg: '获取用户列表失败',
            data: null
        });
    }
});

/* GET user detail by id */
router.get('/detail/:id', async function(req, res) {
    try {
        const userId = req.params.id;
        
        // 获取用户信息和照片
        const sql = `
            SELECT 
                u.*,
                GROUP_CONCAT(p.url) as photo_urls
            FROM users u
            LEFT JOIN photos p ON u.id = p.user_id
            WHERE u.id = ?
            GROUP BY u.id
        `;
        
        const [rows] = await db.pool.query(sql, [userId]);
        
        if (rows.length === 0) {
            return res.status(404).json({
                code: 404,
                msg: '用户不存在',
                data: null
            });
        }

        // 处理照片URL数组
        const userData = {
            ...rows[0],
            photo_urls: rows[0].photo_urls ? rows[0].photo_urls.split(',') : []
        };

        res.status(200).json({
            code: 200,
            msg: '获取用户详情成功',
            data: userData
        });

    } catch (error) {
        console.error('获取用户详情失败:', error);
        res.status(500).json({
            code: 500,
            msg: '获取用户详情失败',
            data: null
        });
    }
});

/* DELETE user by id */
router.delete('/:id', async function(req, res) {
    try {
        const userId = req.params.id;
        
        // 开始事务
        const connection = await db.pool.getConnection();
        await connection.beginTransaction();

        try {
            // 先检查用户是否存在
            const [user] = await connection.query(
                'SELECT id FROM users WHERE id = ?',
                [userId]
            );

            if (user.length === 0) {
                await connection.rollback();
                return res.status(404).json({
                    code: 404,
                    msg: '用户不存在',
                    data: null
                });
            }

            // 删除用户的照片记录
            await connection.query(
                'DELETE FROM photos WHERE user_id = ?',
                [userId]
            );

            // 删除用户记录
            await connection.query(
                'DELETE FROM users WHERE id = ?',
                [userId]
            );

            // 提交事务
            await connection.commit();

            res.status(200).json({
                code: 200,
                msg: '删除用户成功',
                data: null
            });

        } catch (error) {
            await connection.rollback();
            throw error;
        } finally {
            connection.release();
        }

    } catch (error) {
        console.error('删除用户失败:', error);
        res.status(500).json({
            code: 500,
            msg: '删除用户失败',
            data: null
        });
    }
});

// 添加一个测试路由
router.get('/test', (req, res) => {
    res.status(200).json({
        code: 200,
        msg: '服务正常运行',
        data: null
    });
});

module.exports = router;
